package com.clwl.supervise.superviseapp.service;

import cn.hutool.core.date.DateUtil;
import com.clwl.supervise.superviseapp.entity.supervise.JgCheckResultTableSequence;
import com.clwl.supervise.superviseapp.mapper.supervise.JgCheckResultTableSequenceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class SequenceService {

    private final JgCheckResultTableSequenceMapper mapper;

    // 依赖注入代替静态方法
    public SequenceService(JgCheckResultTableSequenceMapper mapper) {
        this.mapper = mapper;
    }

    @Transactional(propagation = Propagation.REQUIRED) // 默认加入当前事务
    public JgCheckResultTableSequence getResultTableSequence() {
        int year = DateUtil.year(new Date());
        // 使用 SELECT FOR UPDATE 锁定记录
        JgCheckResultTableSequence sequence = mapper.selectByYear(year);

        if (sequence == null) {
            sequence = new JgCheckResultTableSequence();
            sequence.setYear(year);
            sequence.setTableIndex(1L);
            mapper.insert(sequence);
        } else {
            sequence.setTableIndex(sequence.getTableIndex() + 1);
            mapper.updateById(sequence);
        }
        return sequence;
    }

    /**
     * 生成检查结果单编号
     * @param companyTypeCode 企业业态编号
     * @param index 当前检查结果表序号
     * @return
     */
    public static String generatorResultTableCode(String companyTypeCode, Long index) {
        String resultCode = DateUtil.year(new Date()) + "-" + companyTypeCode;
        String indexStr = String.format("%06d", index);
        if(index > 999999) {
            //如果总数炒股6位数 那么就不足
            indexStr = String.format("%0"+((index +"").length())+"d", index);
        }
        resultCode = resultCode + "-" + indexStr;
        return resultCode;
    }



    /**
     * 生成生产检查结果单编号
     * @param index 当前检查结果表序号
     * @return
     */
    public static String generatorProResultTableCode(Long index) {
        String resultCode = DateUtil.year(new Date()) + "-1" ;
        String indexStr = String.format("%06d", index);
        if(index > 999999) {
            //如果总数炒股6位数 那么就不足
            indexStr = String.format("%0"+((index +"").length())+"d", index);
        }
        resultCode = resultCode + "-" + indexStr;
        return resultCode;
    }
}

